package pl.un4giv3n.mightvsmagic.action;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;

/**
 * @author andrzejewskia 
 * change user password
 */
public class ActivatePremiumAction extends ProfilePageAction {

	private static final long THIRTY_DAYS = 2592000000L;

	private static final int PREMIUM_COST = 250;

	private static final long serialVersionUID = 1L;

	/**
	 * logged in user
	 */
	private User user;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if(user == null){
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		if(user.getDragonTeeth() < PREMIUM_COST){
			addActionError("Nie masz wystarczającej liczby smoczych zębów, by aktywowac konto premium");
			transaction.rollback();
			entityManager.close();
			return ERROR;
		}else{
			long premiumEndTime = user.getPremiumEndTime();
			if(premiumEndTime < System.currentTimeMillis()){
				premiumEndTime = System.currentTimeMillis();
			}
			premiumEndTime += THIRTY_DAYS;
			user.setPremiumEndTime(premiumEndTime);
			user.setDragonTeeth(user.getDragonTeeth() - PREMIUM_COST);
			entityManager.merge(user);
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.PREMIUM_ACTIVATED, user.getId());
			entityManager.persist(activity);
			entityManager.flush();
			transaction.commit();
			entityManager.close();
		}
		return SUCCESS;
	}
}
